const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 选中的商品id
    idArr: [],
    // 全选变量
    checked: false,
    totalMoney: 0,
    list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function(options) {
    this.getList();
  },

  // 修改购物车商品数量
  updateNum(event) {
    let {
      _id,index
    } = event.currentTarget.dataset;
    console.log(index);
    let buyNum = event.detail;
    let url = '/cart/updateNum';
    let data = {
      _id,
      buyNum
    }
    app.$http.post(url, data).then(res => {
      console.log('修改商品=>成功');
      // 修改list里面商品的数量
      this.data.list[index].buyNum = buyNum;
      this.setData({
        list: this.data.list
      })
      console.log(this.data.list);
    })
  },

  // 单选
  onChange(event) {
    this.setData({
      idArr: event.detail
    });
    let len1 = this.data.idArr.length;
    let len2 = this.data.list.length;
    if (len1 === len2) {
      this.setData({
        checked: true
      })
    } else {
      this.setData({
        checked: false
      })
    }
  },

  // 多选
  selectAll(event) {
    this.setData({
      checked: event.detail
    })
    // 全选
    if (this.data.checked) {
      // 把id提取出来
      let list = this.data.list.map(item => {
        return item._id;
      })
      this.setData({
        idArr: list
      })
    } else {
      this.setData({
        idArr: []
      })
    }
  },

  getList() {
    let url = '/cart/list';
    app.$http.get(url).then(res => {
      this.setData({
        list: res.list
      })
    })
  },

  // 删除商品
  del: function(event) {
    let _id = event.currentTarget.dataset._id;
    let index = event.currentTarget.dataset.index;
    console.log(index);
    let url = '/cart/del?_id=' + _id;
    app.$http.get(url).then(res => {
      this.data.list.splice(index, 1);
      console.log(this.data.list);
      this.setData({
        list: this.data.list
      })
    })
  },

  submit: function() {
    let totalMoney = this.data.totalMoney;
    let goodsId = this.data.idArr;
    let url = '/preOrder/add';
    let data = {
      totalMoney,
      goodsId
    }
    app.$http.post(url, data).then(res => {
      // 把选中的商品对象传过去
      let goodsList = [];
      goodsId.forEach(id=> {
        // 根据id找到商品
        let goods = this.data.list.find(item=> {
          return item._id === id;
        })
        goodsList.push(goods);
      })
      // 订单信息
      let orderInfo = {
        totalMoney,
        goodsList
      }
      let orderInfoStr = JSON.stringify(orderInfo);
      wx.navigateTo({
        url: "/pages/placeOrder/index?orderInfo="+orderInfoStr
      })
    })
  }
})